package com.sciencep.pro.core.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sciencep.pro.common.config.Constant;
import com.sciencep.pro.core.domain.dto.user.UserDetail;
import com.sciencep.pro.core.domain.entity.RolePower;
import com.sciencep.pro.core.dao.RolePowerMapper;
import com.sciencep.pro.core.domain.vo.power.PowerVO;
import com.sciencep.pro.core.service.IRolePowerService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Sciencep
 */
@Service
public class RolePowerServiceImpl extends ServiceImpl<RolePowerMapper, RolePower> implements IRolePowerService {

    @Autowired
    @Lazy
    private IRolePowerService rolePowerService;

    @Override
    public boolean save(String roleId, List<String> powerIds, UserDetail detail) {
        try {
            PowerVO powerVO = new PowerVO();
            powerVO.setRoleId(roleId);
            powerVO.setPowerIds(powerIds);
            powerVO.setCreateUserId(detail.getUserId());
            powerVO.setCreateUserName(detail.getUserName());
            //逻辑删除
            RolePower rolePower = new RolePower();
            rolePower.setIsDel(Constant.IsDelete.YES);
            rolePower.setModifyUserId(detail.getUserId());
            rolePower.setModifyUserName(detail.getUserName());
            baseMapper.update(rolePower, new LambdaQueryWrapper<RolePower>().eq(RolePower::getRoleId, powerVO.getRoleId()));

            //批量权限
            List<RolePower> rolePowerList = new ArrayList<>();
            powerIds.forEach(e -> {
                RolePower rolePower1 = new RolePower();
                rolePower1.setRoleId(roleId);
                rolePower1.setPowerId(Long.valueOf(e));
                try {
                    rolePower1.setCreateUserId(detail.getUserId());
                    rolePower1.setCreateUserName(detail.getUserName());
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                rolePowerList.add(rolePower1);
            });
            return rolePowerService.saveBatch(rolePowerList);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }
}
